import "dart:convert"; // json转换
import "dart:io"; // 网络请求处理
import "data.dart"; //模拟数据

main() async {
  // 开启一个服务监听
  var requestServer = await HttpServer.bind("192.168.1.102", 8080);
  print("http服务已经启动 11");

  // 处理请求
  await for (HttpRequest request in requestServer) {
    handleMessage(request);
  }
}

void handleMessage(HttpRequest request) {
  try {
    if (request.method == "GET") {
      handleGET(request);
    } else if (request.method == "POST") {
      handlePOST(request);
    }
  } catch (e) {
    print("捕获一个异常 $e");
  }
}

void handlePOST(HttpRequest request) {
  // TODO 请求处理
}

void handleGET(HttpRequest request) {
  var action = request.uri.queryParameters['action'];
  if (action == 'getProducts') {
    // var page = request.uri.queryParameters['page'];
    // print("获取产品数据...第$page页");
    request.response
      ..statusCode = HttpStatus.ok
      ..write(json.encode(products))
      ..close();
    return;
  }
  if (action == 'getNews') {
    print("获取新闻数据...");
    request.response
      ..statusCode = HttpStatus.ok
      ..write(json.encode(news))
      ..close();
    return;
  }

  if (action == 'contactCompany') {
    var msg = request.uri.queryParameters['msg'];
    print("获取留言数据为：$msg");
    request.response
      ..statusCode = HttpStatus.ok
      ..write(msg)
      ..close();
    return;
  }
  request.response
    ..statusCode = HttpStatus.ok
    ..write("get request success")
    ..close();
}
